from machine import I2C, Pin
import time,gc
from pcf8574 import PCF8574
from classkeypad import ClassKeypad
from ssd1306 import SSD1306_I2C


i2c = I2C(scl=Pin(2), sda=Pin(0),freq=100000)

display= SSD1306_I2C(128, 64, i2c)
pcf8574=PCF8574(i2c, 0x20)
kp = ClassKeypad(pcf8574)

number=[]
status=True
strs=''
ln=0

def change(v):
    if v=="*":
        return "."
    if v=="#":
        return "="
    if v=="A":
        return "+"
    if v=="B":
        return "-"
    if v=="C":
        return "*"
    if v=="D":
        return "/"
    else:
        return v
    
def get_vals(vaz,display):
    print(type(vaz))
    global number,status,strs
    if vaz in ["0","1","2","3","4","5","6","7","8","9","*"]:
        if len(number)==0:
            number.append(change(vaz))
        else:
            if status:
                number[-1]=number[-1]+change(vaz)
            else:
                number.append(change(vaz))
                status=True
    if vaz in ["A","B","C","D"]:
        if not status:
            if change(vaz) in ["-"]:
                number[-1]=number[-1]+change(vaz)
            else:
                number[-1]=change(vaz)
        else:
            number.append(change(vaz))
        status=False
    dp(display)
    if vaz =="#":
        display.line(0,10+8*ln//16,127,10+8*ln//16,1)
        display.line(0,12+8*ln//16,127,12+8*ln//16,1)
        try:
            end=eval(strs)
        except Exception as e:
            end="error"
        display.text(str(end),0 ,16+8*ln//16,1)
        display.show()
        number=[]
        status=True
        strs=''
    
    
def dp(display):
    global number,strs,ln
    strs=''
    for i in number:
        strs=strs+i
    ln=len(strs)
    display.fill(0)
    j=0
    while j<=ln//16:
        display.text(strs[16*j:16+16*j],0,8*j,1)
        j=j+1
    display.show()

    
while True:
    z=kp.process()
    if z!="None":
        get_vals(z,display)
        print(number)
        time.sleep(0.1)

# * 为小数 # = ABCD +-*/
